package cc.linker.steplink.crm.controller;

import cc.linker.steplink.crm.commons.RandomCodeGenerator;
import cc.linker.steplink.crm.commons.constant.ContentConstant;
import cc.linker.steplink.crm.commons.constant.MongoConstant;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.yzj.YzjRequest;
import cc.linker.steplink.crm.dao.CustomerDao;
import cc.linker.steplink.crm.dao.HelloDao;
import cc.linker.steplink.crm.dao.LevelDao;
import cc.linker.steplink.crm.domain.WxUserInfo;
import cc.linker.steplink.crm.domain.WxUserInfoDto;
import cc.linker.steplink.crm.merchant.dao.EnrollDao;
import cc.linker.steplink.crm.merchant.dao.acs.MerchantInfoDao;
import cc.linker.steplink.crm.merchant.service.acs.XbMerchantService;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.OverViewInfoDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.MerchantWalletDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantWalletService;
import cc.linker.steplink.crm.merchanth5.service.tl.LedgerProcessService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.CustomerService;
import cc.linker.steplink.crm.service.PersonalService;
import cc.linker.steplink.crm.task.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * demo restful api
 * 测试程序
 *
 * @author zhaomengwei
 */
@Slf4j
@RestController
public class HelloController {

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private HttpService httpService;

    @Autowired
    private HelloDao helloDao;

    @Autowired
    private MerchantSalerService merchantSalerService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private GroupStatistics groupStatistics;

    @Autowired
    private GoodsSkuLockTask goodsSkuLockTask;

    @Autowired
    private PublicMenuTask publicMenuTask;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RequestFilter requestFilter;

    @Autowired
    private MerchantWalletService merchantWalletService;

    @Autowired
    private XbMerchantService xbMerchantService;

    @Autowired
    private PersonalService personalService;

    @Autowired
    private LedgerProcessService ledgerProcessService;
    @Autowired
    private OverViewInfoDao overViewInfoDao;
    @Autowired
    private MallDao mallDao;
    @Autowired
    private MerchantWalletDao merchantWalletDao;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private ScoreActivityTask scoreActivityTask;
    @Autowired
    private AnalysePropagationLinkTask analysePropagationLinkTask;
    @Autowired
    private SyncPropagationLinkTask syncPropagationLinkTask;
    @Autowired
    private EnrollDao enrollDao;
    @Autowired
    private LevelDao levelDao;

    @Autowired
    private MerchantInfoDao merchantInfoDao;

    @Autowired
    private SyncPublicUserDataTask syncPublicUserDataTask;

    @Autowired
    private YzjRequest yzjRequest;
    @Value("${yzj.orgId}")
    public String yzjOrgId;

    @Autowired
    private CustomerService customerService;

    private Integer finallCount = 0;

    @Autowired
    private GiftTaskTask giftTaskTask;

    @RequestMapping(value = {"/hello"})
    public String hello() {
        return "hello";
    }

    @RequestMapping(value = {"/doscore"})
    public void doscore(String day) {
        scoreActivityTask.execute(day);
    }

    @RequestMapping(value = {"/gifttask"})
    public void giftTask() {
        giftTaskTask.execute();
    }


//    @RequestMapping(value = {"/analysePropagation"})
//    public void analysePropagation(String day)
//    {
//        analysePropagationLinkTask.invoke(day);
//    }

//    @RequestMapping(value = {"/doanalyse"})
//    public void doanalyse(String day)
//    {
//        syncPropagationLinkTask.execute();
//        analysePropagationLinkTask.execute(day);
//        scoreActivityTask.execute(day);
//    }

    @RequestMapping(value = {"/helloworld"})
    public String helloWorld() {
        return "hello world";
    }

    @RequestMapping(value = {"/getOrgInfoByLogin"})
    public Object getOrgInfoByLogin(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        return merchantSalerService.getOrgInfo(wxUser.getOrgId());
    }

    /**
     * @Description：同步系统历史的等级到雅智捷
     * @DateTime：2020/12/17 9:49
     * @Params：
     * @Return：
     */
    @RequestMapping(value = {"/syncLevelYZJ"})
    public void syncLevelYZJ() {
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", yzjOrgId);
        map.put("pn", 1);
        map.put("pageSize", 10);
        List<Map<String, Object>> list = levelDao.listLevels(map);
        if (list != null) {
            for (Map<String, Object> levelMap : list) {
                this.yzjRequest.addMemberInfo((String) levelMap.get("levelName"), (String) levelMap.get("levelId"), (String) levelMap.get("orgId"));
            }
        }
    }

    /**
     * @Description：同步历史用户等级到雅智捷
     * @DateTime：2020/12/17 9:48
     * @Params：
     * @Return：
     */
    @RequestMapping(value = {"/syncCustomerLevelToYZJ"})
    public void syncCustomerLevelToYZJ() {
        List<Map<String, Object>> customerList = this.levelDao.getCustomerListByLevel(yzjOrgId);
        if (customerList != null) {
            for (Map<String, Object> customerMap : customerList) {
                this.yzjRequest.alterMemberLevel((String) customerMap.get("sourceUserId"), "", (String) customerMap.get("levelId"), yzjOrgId);
            }
        }
    }

    /**
     * @Description：同步历史的店铺信息到雅智捷
     * @DateTime：2020/12/17 9:49
     * @Params：
     * @Return：
     */
    @RequestMapping(value = {"/syncStoreToYZJ"})
    public void syncStoreToYZJ() {
        Map<String, Object> storeParams = new HashMap<>();
        storeParams.put("orgId", yzjOrgId);
        List<Map<String, Object>> storeList = this.merchantInfoDao.getMerchantListByOrgId(yzjOrgId);
        for (Map<String, Object> storeMap : storeList) {
            String type = storeMap.get("customerType").toString();
            storeParams.put("storeId", type.equals("2") ? storeMap.get("customerId").toString() : storeMap.get("orgId").toString());
            storeParams.put("storeName", storeMap.get("storeName").toString());
            this.yzjRequest.createOrUpdateStore(storeParams);
        }
    }

    /******商品缓存*******/
    /**
     * 填充商品和sku库存缓存
     */
    @RequestMapping(value = {"/goodsSkuLockTask"})
    public void goodsSkuLockTask() {
        goodsSkuLockTask.goodsSkuLockTask();
    }

    /**
     * 删除商品和sku库存缓存
     */
    @RequestMapping(value = {"/goodsSkuLockTaskFlush"})
    public void goodsSkuLockTaskFlush() {
        goodsSkuLockTask.goodsSkuLockTaskFlush();
    }

    /**
     * 删除所有缓存
     */
    @RequestMapping(value = {"/flushAllGoodsCache"})
    public void flushAllGoodsCache() {
        goodsSkuLockTask.flushAllGoodsCache();
    }

    /******商品缓存*******/

    @RequestMapping(value = {"/setScoreLog"})
    public void setScore() {
        helloDao.flushScoreLog();
        List<String> customerIdList = helloDao.getCustomerId();
        for (String customerId : customerIdList) {
            List<Map<String, Object>> coinList = merchantWalletDao.coinList(customerId);
            if (null != coinList && coinList.size() > 0) {
                for (Map<String, Object> da : coinList) {
                    da.put("customerId", customerId);
                    da.put("score", da.get("amount"));
                    purchaseProcessDao.addScoreLogTask(da);
                }
            }
        }
    }


    @RequestMapping(value = {"/groupstatistics"})
    public void groupStatistics() {
        groupStatistics.doStatistics();
    }

    @RequestMapping(value = {"/setpromoterorder"})
    public void setpromoterorder() {
        List<String> orderSn = helloDao.getAllOrderSn();
        List<String> orderSn2 = helloDao.getAllOrderSn2();
        List<String> orderSn3 = helloDao.getAllOrderSn3();
        for (String od : orderSn) {
            helloDao.addPromoterOrder(od);
        }
        for (String od : orderSn2) {
            helloDao.addPromoterOrder(od);
        }
        for (String od : orderSn3) {
            helloDao.addPromoterOrder(od);
        }
    }

    @RequestMapping(value = {"/delsettlement"})
    public void delsettlement(@RequestParam(value = "password", defaultValue = "") String password,
                              @RequestParam(value = "time", defaultValue = "") String time) {
        if ("link".equals(password)) {
            if (StringUtils.isEmpty(time)) {
                time = null;
            }
            helloDao.delsettlement(time);
        } else {
            throw GlobalException.build("朋友。不要乱调接口");
        }
    }

    @RequestMapping(value = {"/settlementMonth"})
    public void settlementMonth(@RequestParam(value = "password", defaultValue = "") String password,
                                @RequestParam(value = "year") Integer year,
                                @RequestParam(value = "month") Integer month
    ) {
        if ("link".equals(password)) {
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month, 1);
            long next = calendar.getTimeInMillis();
            calendar.add(Calendar.MONTH, -1);
            while (calendar.getTimeInMillis() != next) {
                String yearStr = calendar.get(Calendar.YEAR) + "";//获取年份
                int months = calendar.get(Calendar.MONTH) + 1;//获取月份
                String monthStr = months < 10 ? "0" + months : months + "";
                int day = calendar.get(Calendar.DATE);//获取日
                String dayStr = day < 10 ? "0" + day : day + "";
                String ymd = yearStr + "-" + monthStr + "-" + dayStr;
                settlement(ymd);
//                System.out.println(ymd);
                int i = 1;
                calendar.add(Calendar.DAY_OF_MONTH, i++);
            }
        } else {
            throw GlobalException.build("朋友。不要乱调接口");
        }
    }


    @RequestMapping(value = {"/addbalance"})
    public void addbalance(@RequestParam(value = "password", defaultValue = "") String password, @RequestParam(value = "ymd") String ymd) {
        if ("link".equals(password)) {
            merchantSalerService.addbalance(ymd);
        } else {
            throw GlobalException.build("朋友。不要乱调接口");
        }
    }

    @RequestMapping(value = {"/settlementDay"})
    public void settlementDay(@RequestParam(value = "password", defaultValue = "") String password,
                              @RequestParam(value = "ymd") String ymd) {
        if ("link".equals(password)) {
            settlement(ymd);
        } else {
            throw GlobalException.build("朋友。不要乱调接口");
        }
    }

    private void settlement(String time) {

        String strStart = time + " 00:00:00";
        String strEnd = time + " 23:59:59";

        //获取所有加盟代理
        List<Map<String, Object>> allPromoterList = merchantSalerService.getAllPromoterList();
        for (Map<String, Object> da : allPromoterList) {
            String customerId = da.get("customerId").toString();
            String orgId = da.get("orgId").toString();
            Map<String, Object> param = new HashMap<>();
            param.put("orgId", orgId);
            param.put("customerId", customerId);
            param.put("startTime", strStart);
            param.put("endTime", strEnd);
            param.put("createDate", time);

            Integer sonCount = merchantSalerService.getTodaySonCount(param);//当天新增下级人数
            param.put("sonCount", sonCount);

            Integer orderCount = merchantSalerService.getSonOrderCount(param);
            param.put("orderCount", orderCount);

            Integer allRebate = merchantSalerService.getTodayAllRebate(param);//当天收到返润金额总额 单位分
            param.put("allRebate", allRebate);

            Integer serviceFee = merchantSalerService.getTodayServiceFee(param);//当天服务费 单位分
            param.put("serviceFee", serviceFee);

            Integer recommendFee = merchantSalerService.getTodayRecommendFee(param);//当天推荐费 单位分
            param.put("recommendFee", recommendFee);

            Long sonDealFee = merchantSalerService.getUserTotalVolume(customerId, 1, orgId, strStart, strEnd);//当天下级交易额 单位分
            param.put("sonDealFee", Integer.parseInt(sonDealFee.toString()));

            Long promoterDealFee = merchantSalerService.getUserTotalVolume(customerId, 2, orgId, strStart, strEnd);//当天下级代理交易额 单位分
            param.put("promoterDealFee", Integer.parseInt(promoterDealFee.toString()));

            merchantSalerService.saveAchievementSettlement(param);
        }


    }


    @RequestMapping(value = {"/resetarticles"})
    public String resetArticles() throws IOException, URISyntaxException {
        String url = systemProperties.getSync().getContentUrl() + ContentConstant.GET_ARTICLE_DETAIL;
        List<Map<String, Object>> list = helloDao.list();
        for (Map<String, Object> data : list) {
            String artId = (String) data.get("articleId");
            Map<String, Object> param = new HashMap<>();
            param.put("newsId", artId);
            JSONObject jsonObject = (JSONObject) JSONArray.toJSON(param);
            String postres = httpService.doPost(url, jsonObject.toJSONString(), ContentConstant.JSON_HEADER);
            if (StringUtils.isEmpty(postres)) {
                continue;
            }
            Map parse = (Map) JSON.parse(postres);
            Map res = (Map) parse.get("data");
            Map<String, String> resData = new HashMap<>();
            resData.put("url", (String) res.get("url"));
            resData.put("articleId", artId);
            helloDao.saveUrl(resData);
        }
        return "done";
    }

    @GetMapping("/buy")
    public void buy() {
        List<Map<String, Object>> maps = helloDao.listBuy();
        for (Map<String, Object> map : maps) {
            String datetime = map.get("datetime").toString();
            datetime = datetime.substring(0, 19);
            map.put("datetime", datetime);
            map.put("buyCount", 1);
            mongoTemplate.insert(map, MongoConstant.GOODS_DATA);
        }
    }

    @GetMapping("/updateSkuSalesNum")
    public void updateSkuSalesNum() {
        //销量归零
        helloDao.setSkuSalesZero();
        List<Map<String, Object>> maps = helloDao.getSkuOrder();
        for (Map<String, Object> map : maps) {
            mallDao.editGoodSkuSalesNum(map);
            if (!StringUtils.isEmpty(map.get("mallsSkuId"))) {
                mallDao.editMallGoodSkuSalesNumZ(map);
            }
        }
    }


    @GetMapping("/del")
    public void del() {
        helloDao.delete();
    }

    @GetMapping("/fix")
    public void fix() {
        Query query = new Query();
        query.addCriteria(Criteria.where("type").is(3));

        List<Map> maps = mongoTemplate.find(query, Map.class, MongoConstant.GOODS_DATA);
        for (Map map : maps) {
            Object datetime = map.get("datetime");
            if (datetime instanceof Date) {
                System.out.println(datetime);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = simpleDateFormat.format(datetime);
                System.out.println(format);
                Query query1 = new Query();
                query1.addCriteria(Criteria.where("_id").is(map.get("_id")));
                Update update = new Update();
                update.set("datetime", format);
                mongoTemplate.updateFirst(query1, update, MongoConstant.GOODS_DATA);


            }

        }

    }

    @RequestMapping(value = {"/updateSubscribe"})
    public String addbalance(@RequestParam(value = "password", defaultValue = "") String password) {
        if ("link".equals(password) && finallCount == 0) {
            List<Map<String, Object>> customers = customerDao.getAllCustomerHavingOpenidAndTokenOne();
            Map<String, Object> map = new HashMap<>();
            map.put("action", "getWeixinUserInfo");
            for (Map<String, Object> customer : customers) {
                String openId = (String) customer.get("openId");
                String token = (String) customer.get("token");
                map.put("openid", openId);
                map.put("token", token);
                String result;
                try {
                    result = httpService.doPost(systemProperties.getWxpushurl(), com.alibaba.fastjson.JSON.toJSONString(map));
                } catch (Exception e) {
                    LOGGER.error("矩阵调用异常");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    continue;
                }
                WxUserInfoDto wxUserInfoDto = com.alibaba.fastjson.JSON.parseObject(result, WxUserInfoDto.class);
                if (wxUserInfoDto != null && "200".equals(wxUserInfoDto.getErrcode())) {
                    WxUserInfo data = wxUserInfoDto.getData();
                    if (data != null) {
                        Integer subscribe = data.getSubscribe();
                        if (subscribe != null) {
                            customer.put("subscribe", subscribe);
                            customerDao.updateSubscribeByCustomerId(customer);
                        }
                    }
                }
                // 休息一下
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            finallCount = 1;
            return "修改完成！";
        } else {
            throw GlobalException.build("朋友。不要乱调接口");
        }
    }

    @GetMapping("/publicMenuCache")
    public void publicMenuCache() {
        publicMenuTask.publicMenuTokens();
    }

//    @GetMapping("/addGoodsData")
//    public String addGoodsData(String[] orgIds) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where("orgId").nin(orgIds));
//        List<Map> maps = mongoTemplate.find(query, Map.class, MongoConstant.GOODS_DATA);
//        if(maps!=null && maps.size()>0){
//            for(Map map :maps){
//                if(StringUtils.isEmpty(map.get("goodsId"))){
//                    map.put("goodsId",null);
//                }
//                overViewInfoDao.addGoodsData(map);
//            }
//        }
//        return "ok";
//    }

    @RequestMapping(value = {"/updateAttrValue"})
    public String updateAttrValue() {
        List<String> attrIds = enrollDao.getattrIdsByPicture();
        for (String attrId : attrIds) {
            List<Map> lismap = enrollDao.getRecordByAttrId(attrId);
            for (Map map : lismap) {
                String recordsString = map.get("record").toString();
                JSONArray records = JSONArray.parseArray(recordsString);
                List<Map> newrecords = new ArrayList<>();
                if (records != null && records.size() > 0) {
                    for (int i = 0; i < records.size(); i++) {
                        JSONObject record = records.getJSONObject(i);
                        String aattrId = "";
                        if (!StringUtils.isEmpty(record.get("attrId"))) {
                            aattrId = record.get("attrId").toString();
                        }
                        if (attrId.equals(aattrId)) {
                            //修改格式
                            if (!StringUtils.isEmpty(record.get("attrValue"))) {
                                String attrValue = record.get("attrValue").toString();
                                List<Map> a = new ArrayList<>();
                                Map b = new HashMap();
                                b.put("resId", "");
                                b.put("sourceUrl", attrValue);
                                b.put("previewUrl", attrValue);
                                b.put("type", 1);
                                a.add(b);
                                record.put("attrValue", a);
                            }
                        }
                        newrecords.add(record);
                    }
                }
                map.put("record", JSON.toJSONString(newrecords));
                enrollDao.updateEnrollRecord(map);
            }
        }
        System.out.println("1");
        return "ok";
    }


    @RequestMapping(value = {"/yzjCustomerSync"})
    public String yzjCustomerSync() {
        //查询雅智捷机构绑定手机号未同步的用户
        List<Map> customers = helloDao.getCustomersByYzj(yzjOrgId);
        if (customers != null && customers.size() > 0) {
            for (Map customer : customers) {
                String sourceUserId = RandomCodeGenerator.generateShortUuid();
                Map member = new HashMap();
                member.put("full_name", customer.get("full_name"));
                member.put("mobile", customer.get("mobile"));
                member.put("member_code", sourceUserId);
                if (yzjRequest.addMember(member)) {
                    //同步成功
                    customer.put("sourceUserId", sourceUserId);
                    helloDao.updateCustomerSourceUserId(customer);
                    if (!StringUtils.isEmpty(customer.get("customerlevelId"))) {
                        yzjRequest.alterMemberLevel(sourceUserId, "", customer.get("customerlevelId").toString(), customer.get("orgId").toString());
                    }
                }
            }
        }
        return "ok";
    }

    @RequestMapping(value = {"/syncWxCustomer"})
    public void syncWxCustomer() {
        this.syncPublicUserDataTask.doSync("10145");
    }
}
